package com.dhh.sky.activity;

import java.util.Arrays;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Config;
import com.dhh.sky.util.Constant;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;

public class NavigateActivity extends SherlockFragmentActivity{
	private SDAApplication app;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.splash);
		app = (SDAApplication)this.getApplication();		
	}
	
	@Override 
	public void onResume(){
		super.onResume();
		if(hasLogin()){
			initConnection();
		}else{
			Intent intent = new Intent(this,SDAActivity.class);
			startActivity(intent);
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}
	
	private boolean hasLogin(){
		boolean flag = false;
		SharedPreferences sp = this.getSharedPreferences("com.microsoft.live", Context.MODE_PRIVATE);
		String token = sp.getString("refresh_token", null);
		
		if(token!=null && token.trim().length()>0){
			flag = true;
		}
		
		return flag;
	}
	
	private void initConnection(){
		try{
			if(CUtil.isNetworkAvailable(this)){
				if(!app.isConnected()){
					final LiveAuthClient aClient = new LiveAuthClient(this,Config.CLIENT_ID);
					aClient.initialize(Arrays.asList(Config.SCOPES), new LiveAuthListener(){
			            @Override
			            public void onAuthError(LiveAuthException exception, Object userState) {
			            	toFileListView();
			            }

			            @Override
			            public void onAuthComplete(LiveStatus status,LiveConnectSession session,Object userState) {
			                if (status==LiveStatus.CONNECTED) {
			                	app.setAuthClient(aClient);
			                	app.setSession(session);
			                    app.setConnectClient(new LiveConnectClient(session));
			                }
			                
			                toFileListView();
			            }
			        });
				}else{
					toFileListView();
				}
			}else{
				toFileListView();
			}
		}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(), e);
		}
	}
	
	private void toFileListView(){
		Intent intent = new Intent(this,FileListActivity.class);
		startActivity(intent);
	}
	
}
